import Vue from 'vue'
import Router from 'vue-router'
import Main from '@/containers/Main.vue'
import Person from '@/containers/Person.vue'
import User from '@/containers/User.vue'
import Login from "@/views/Login";
import Index from "@/views/Index";

Vue.use(Router);

const router = new Router({
    mode:'history',
    routes: [
        {
            path: '/',
            redirect:'/index/main'
        },
        {
            path: '/login',
            name: 'Login',
            component: Login,
        },
        {
            path: '/index',
            name: 'Index',
            component: Index,
            children: [
                {
                    path: 'main',
                    name: 'Main',
                    component: Main
                },
                {
                    path: 'person',
                    name: 'Person',
                    component: Person,
                    children: [
                        {
                            path: 'user',
                            name: 'User',
                            component: User
                        }
                    ]
                },
            ],
        },
    ]
});

/**
 * @param {to} 将要去的路由
 * @param {from} 出发的路由
 * @param {next} 执行下一步
 */
router.beforeEach((to, from, next) => {
    let loginState = sessionStorage.getItem('loginState');
    let flag = loginState && loginState=='true';
    if (to.path == '/login' || flag){
        next();
    }else {
        next({
            path:'/login'
        });
    }
});

const originalPush = Router.prototype.push;
Router.prototype.push = function push(location) {
    return originalPush.call(this, location).catch(err => err)
};

export default router;

